﻿using CompanyManageSystem.DLL;
using CompanyManageSystem.Model;
using CompanyManageSystem.Service;
using DevExpress.XtraEditors.DXErrorProvider;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CompanyManageSystem.UI.Repast
{
    public partial class Frm_PurchaseStorageOrderDetailAdd : BaseXtraForm
    {
        #region 属性
        Guid? HeaderID;

        public DateTime SaveTime { get; set; }

        public event EventHandler SaveEvent;

        List<PurchaseStorageOrderDetail> DataList;
        #endregion
        public Frm_PurchaseStorageOrderDetailAdd(EStatus status, Guid? headerId = null)
        {
            InitializeComponent();
            this.FStatus = status;
            this.HeaderID = headerId;
            this.DataList = new List<PurchaseStorageOrderDetail>();
            this.BindCheckEdit(gridView1, false, false);
            this.BindRowIndicator(gridView1);

            //加载数据
            var rservice = new RepastService();
            SupplierID.Properties.DataSource = rservice.GetAllSuppliers();
            repositoryItemSearchLookUpEdit1.DataSource = rservice.GetAllMaterial();
        }

        /// <summary>
        /// 窗体加载完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Frm_PurchaseStorageOrderDetail_Load(object sender, EventArgs e)
        {
            switch (this.FStatus)
            {
                case EStatus.Add:
                    this.OrderNum.Text = "PS" + DateTime.Now.ToString("yyyyMMddhhmmss");
                    this.StorageTime.DateTime = DateTime.Now;

                    IsLockTool(true);
                    this.barButtonItem1.Enabled = true;
                    this.barButtonItem3.Enabled = true;
                    this.barButtonItem6.Enabled = true;
                    this.Text = "采购入库单-添加";
                    break;
                case EStatus.Modify:
                    SetHeaderAndDetailValue();

                    this.Text = "采购入库单-编辑";
                    break;
                case EStatus.Look:
                    SetHeaderAndDetailValue();

                    this.Text = "采购入库单-查看";
                    break;
            }

        }

        /// <summary>
        /// 添加主单和明细数据的方法
        /// </summary>
        public void SetHeaderAndDetailValue()
        {
            RepastService rservice = new RepastService();
            var header = rservice.GetPurcahseOrderByID(this.HeaderID);

            OrderNum.Text = header.OrderNum;
            SupplierID.EditValue = header.SupplierID;
            StorageTime.DateTime = header.StorageTime;
            Style.Text = header.Style == "0" ? "现金" : "月结";
            Remark.Text = header.Remark;
            CreateTime.DateTime = header.CreateTime;

            gridControl1.DataSource = rservice.GetPurcahseStorageDetailByHeaderID(this.HeaderID);

            this.DataList = (List<PurchaseStorageOrderDetail>)gridControl1.DataSource;
            this.SaveTime = header.CreateTime;

            //已审批的无法保存
            if (header.Examine == "1")
            {
                this.barButtonItem4.Enabled = false;
                this.barButtonItem5.Enabled = true;
                this.barButtonItem6.Enabled = false;
            }
            else
            {
                this.barButtonItem4.Enabled = true;
                this.barButtonItem5.Enabled = false;
                this.barButtonItem6.Enabled = true;
            }
        }

        /// <summary>
        /// 采购订货
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Frm_PurchaseStorageAdd frm = new Frm_PurchaseStorageAdd();
            frm.SaveEvent += StorageAdd_SaveEvent;
            frm.ShowDialog();
        }
        private void StorageAdd_SaveEvent(Object sender, EventArgs e)
        {
            var orderDetail = sender as List<PurchaseOrderDetail>;
            var storageDetail = new List<PurchaseStorageOrderDetail>();
            foreach (var item in orderDetail)
            {
                var detail = new PurchaseStorageOrderDetail
                {
                    MaterialID = item.MaterialID,
                    MaterialName = item.MaterialName,
                    Number = item.Number,
                    Unit = item.Unit,
                    Price = item.Price,
                    Money = item.Money,
                    Canteen = item.Canteen,
                    Stall = item.Stall,
                    Remark = item.Remark,
                };
                this.DataList.Add(detail);
            }

            //for (int i = 0; i < list.Count(); i++)
            //{
            //    if (ListData.Contains(storageDetail[i]))
            //    {
            //        list.Remove(list[i]);
            //        i--;
            //    }
            //}

            gridControl1.DataSource = this.DataList;
            gridControl1.RefreshDataSource();
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem6_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //关闭GridView的编辑状态
            gridView1.CloseEditor();

            //检查各个数据是否有效
            bool validate = InitValidationRules();
            if (validate == false)
            {
                return;
            }

            RepastService rservice = new RepastService();
            PurchaseStorageOrder header = null;

            if (this.FStatus == EStatus.Add)
            {
                Guid headerId = SaveHeaderInfo();
                var list = (List<PurchaseStorageOrderDetail>)gridControl1.DataSource;
                rservice.AddStorageOrder(list, headerId);
            }
            else if (this.FStatus == EStatus.Modify)
            {
                SaveHeaderInfo(this.HeaderID);
                header = rservice.GetPurcahseOrderByID(this.HeaderID);

                //先把原来的删除再添加新的明细
                rservice.DelPurchaseDetailByHeaderID(this.HeaderID);

                var list = (List<PurchaseStorageOrderDetail>)gridControl1.DataSource;
                rservice.AddStorageOrder(list, (Guid)this.HeaderID);

                ShowInfo("编辑成功!");
            }

            if (SaveEvent != null)
            {
                SaveEvent(header, new EventArgs());
            }
            this.Close();
        }

        /// <summary>
        /// 保存采购入库主单信息方法
        /// </summary>
        /// <param name="billHeaderID"></param>
        /// <returns></returns>
        private Guid SaveHeaderInfo(Guid? billHeaderID = null)
        {
            PSContext _db = new PSContext();
            var info = new PurchaseStorageOrder();

            if (billHeaderID == null)
            {
                info = new PurchaseStorageOrder
                {
                    ID = Guid.NewGuid(),
                    OrderNum = OrderNum.Text,
                    SupplierID = (Guid)SupplierID.EditValue,
                    StorageTime = StorageTime.DateTime,
                    Style = Style.Text == "现金" ? "0" : "1",
                    Remark = Remark.Text,
                    CreateTime = DateTime.Now,
                    Creator = "管理员",
                    ExamineTime = DateTime.Now,
                    Examine = "0"
                };
                _db.PurchaseStorageOrders.Add(info);
            }
            else
            {
                var header = _db.PurchaseStorageOrders.Find(billHeaderID);
                header.OrderNum = OrderNum.Text;
                header.SupplierID = (Guid)SupplierID.EditValue;
                header.StorageTime = StorageTime.DateTime;
                header.Style = Style.Text == "现金" ? "0" : "1";
                header.Remark = Remark.Text;
            }
            _db.SaveChanges();
            return info.ID;
        }

        /// <summary>
        /// 判断各个数据是否为空方法
        /// </summary>
        private bool InitValidationRules()
        {
            if (this.DataList.Count == 0)
            {
                ShowInfo("明细数据不能为空!");
                return false;
            }
            if (OrderNum.Text.Equals(""))
            {
                ShowInfo("订单号不能为空!");
                return false;
            }
            if (SupplierID.EditValue.Equals(""))
            {
                ShowInfo("供应商不能为空!");
                return false;
            }
            if (Style.Text.Equals(""))
            {
                ShowInfo("结算方式不能为空!");
                return false;
            }
            return true;
        }

        /// <summary>
        /// 表格内容改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            RepastService rservice = new RepastService();
            if (e.Column.FieldName == "MaterialID")
            {
                var materialID = gridView1.GetFocusedRowCellValue(e.Column);
                var materialName = rservice.GetMaterialNameByID((Guid)materialID);
                var materialUnit = rservice.GetMaterialUnitByID((Guid)materialID);
                gridView1.SetFocusedRowCellValue("MaterialName", materialName);
                gridView1.SetFocusedRowCellValue("Unit", materialUnit);
                gridControl1.RefreshDataSource();
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var detail = this.GetChecked<PurchaseStorageOrderDetail>(gridView1);
            if (detail.Count == 0)
            {
                ShowInfo("请勾选明细!");
                return;
            }

            if (ShowQuestion($"是否删除{detail.Count}条明细?"))
            {
                this.DataList = this.DataList.Where(p => p.IsChecked == false).ToList();
                gridControl1.DataSource = this.DataList;
                gridControl1.RefreshDataSource();
                ShowInfo($"成功删除{detail.Count}条明细!");
            }

        }

        /// <summary>
        /// 是否说定工具栏
        /// </summary>
        /// <param name="isLock"></param>
        public void IsLockTool(bool isLock)
        {
            if (isLock)
            {
                this.barButtonItem4.Enabled = false;
                this.barButtonItem5.Enabled = false;
                this.barButtonItem6.Enabled = false;
                this.barButtonItem7.Enabled = false;
                this.barButtonItem8.Enabled = false;
            }
            else
            {
                this.barButtonItem4.Enabled = true;
                this.barButtonItem5.Enabled = true;
                this.barButtonItem6.Enabled = true;
                this.barButtonItem7.Enabled = true;
                this.barButtonItem8.Enabled = true;
            }
        }

        #region 上一张/下一张
        /// <summary>
        /// 上一张
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem7_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RepastService rservice = new RepastService();
            var header = rservice.GetPrevPurchaseStorageOrder(this.SaveTime);

            PrevNextBill(header, 0);
        }

        /// <summary>
        /// 下一张
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem8_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RepastService rservice = new RepastService();
            var header = rservice.GetNextPurchaseStorageOrder(this.SaveTime);

            PrevNextBill(header, 1);
        }

        /// <summary>
        /// 上一张/下一张方法
        /// </summary>
        /// <param name="header"></param>
        /// <param name="num"></param>
        public void PrevNextBill(PurchaseStorageOrder header, int num)
        {
            IsLockTool(false);

            if (header != null)
            {
                this.HeaderID = header.ID;

                //这里需要new一个
                this.DataList = new List<PurchaseStorageOrderDetail>();
                SetHeaderAndDetailValue();
                this.SaveTime = header.CreateTime;
            }
            else
            {
                var msg = num == 0 ? "已经是第一张了!" : "已经是最后一张了!";
                ShowInfo(msg);
            }
        }
        #endregion

        #region 审批/弃审
        /// <summary>
        /// 审批
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem4_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ChangeExamine(this.HeaderID, "1");
        }

        /// <summary>
        /// 弃审
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ChangeExamine(this.HeaderID, "0");
        }

        /// <summary>
        /// 审批/弃审方法
        /// </summary>
        /// <param name="headerId"></param>
        /// <param name="num"></param>
        public void ChangeExamine(Guid? headerId, string num)
        {
            IsLockTool(false);
            RepastService rservice = new RepastService();
            rservice.ChangeExamineStatusByID(headerId, num);

            if (num == "1")
            {
                this.barButtonItem4.Enabled = false;
                this.barButtonItem6.Enabled = false;
            }
            else
            {
                this.barButtonItem5.Enabled = false;
            }

            if (SaveEvent != null)
            {
                SaveEvent(null, new EventArgs());
            }
        }
        #endregion

    }
}
